package main

import (
	"bufio"
	"fmt"
	"math/big"
	"os"
	"strings"

	"gitee.com/thubcc/blockchain/constant"

	"github.com/ethereum/go-ethereum/common"
	"github.com/ethereum/go-ethereum/crypto"
	"github.com/ethereum/go-ethereum/log"
	"github.com/ethereum/go-ethereum/p2p"
	"github.com/ethereum/go-ethereum/p2p/enode"
	"github.com/ethereum/go-ethereum/p2p/nat"
	"github.com/ethereum/go-ethereum/params"
)



func main() {
	logHandler,err := log.NetHandler("udp", "localhost:9000", log.JSONFormat())
	if err != nil {
		fmt.Println(err)
	}
	log.Root().SetHandler(log.LvlFilterHandler(log.Lvl(6),logHandler))

	peer := enode.MustParse(constant.DefaultNode)
	var peers = []*enode.Node{peer}
	for _,mainnode := range params.MainnetBootnodes {
		peer := enode.MustParse(mainnode)
		peers = append(peers,peer)
	}
	
	prk,_ := big.NewInt(0).SetString(constant.DefaultPrivateKeyStart,16)
	asymKey,_ := crypto.ToECDSA(prk.Bytes())

	var nullRun = func(p *p2p.Peer,rw p2p.MsgReadWriter) error {return nil}
	
	protocol := p2p.Protocol{
		Name:"nil",
		Version:1,
		Length:256,
		Run:nullRun,
	}
	maxPeers := 50
	var server = &p2p.Server{
		Config: p2p.Config{
			PrivateKey:     asymKey,
			MaxPeers:       maxPeers,
			Name:           common.MakeName("p2p find", "6.0"),
			Protocols:      []p2p.Protocol{protocol},
			NAT:            nat.Any(),
			BootstrapNodes: peers,
			StaticNodes:    peers,
			TrustedNodes:   peers,
		},
	}
	server.Start()
	defer server.Stop()
	input := bufio.NewReader(os.Stdin)
	fmt.Println()
	for {
		fmt.Printf("~Q for exit:")
		txt, err := input.ReadString('\n')
		if err != nil {
			fmt.Println("\n ~Q for exit:",err)
		} else {
			txt = strings.TrimRight(txt, "\n\r")
			if txt == "~Q" {
				break
			}
			fmt.Println(txt)
		}
	}
}
